<template>
    <div class="wh-100% flex flex-col gap-10px overflow-scroll">
        <search-card />
        <n-card class="h-full" title="预约单列表">
            <template #header-extra>
                <div class="flex gap-10px">
                    <n-button
                        ghost
                        size="small"
                        :focusable="false"
                        @click="handleRefreshPage"
                    >
                        <template #icon>
                            <n-icon :component="RefreshCircle" />
                        </template>
                        刷新
                    </n-button>
                </div>
            </template>
            <n-data-table
                :loading="loading"
                :columns="columns"
                :data="currentReservations"
            />
            <template #footer>
                <div class="w-full flex justify-end">
                    <n-pagination
                        v-model:page="pagination.page"
                        :page-count="
                            Math.ceil(pagination.total / pagination.size)
                        "
                        @update:page="handleChangePage"
                    >
                        <template #prefix>
                            <span>共 {{ pagination.total }} 条</span>
                        </template>
                    </n-pagination>
                </div>
            </template>
        </n-card>
        <n-drawer
            v-model:show="detailDrawervisible"
            :auto-focus="false"
            width="500"
            placement="right"
        >
            <n-drawer-content title="预约详情">
                <reservation-detail
                    :model="'reserve'"
                    :reservation="currentReservation!"
                    :detail="currentReservationDetail!"
                />
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { h, ref, reactive, onMounted } from "vue";
import { RefreshCircle } from "@vicons/ionicons5";

import { NTag, NButton } from "naive-ui";
import type { DataTableColumns } from "naive-ui";

import type { Customer } from "@/service/api/types/user";
import type { MeetingRoom } from "@/service/api/types/room";
import type { Reservation, Order } from "@/service/api/types/reservation";

import {
    getReservationDetail,
    getReservationsByStatus,
    getReservationCountsByStatus,
} from "@/service/api/modules/reservation";

import SearchCard from "../components/search-card/index.vue";
import ReservationDetail from "../components/reservation-detail/index.vue";

interface ReservationDetail {
    order: Order;
    customer: Customer;
    meetingRoom: MeetingRoom;
}

const loading = ref(false);
const detailDrawervisible = ref(false);

// 状态映射 -> 标签类型和标签文字
const statusMap: { [key: string]: { type: string; label: string } } = {
    verifying: { type: "info", label: "待审核" },
    rejected: { type: "error", label: "被拒绝" },
    confirmed: { type: "success", label: "待使用" },
    refunded: { type: "warning", label: "已退款" },
    completed: { type: "default", label: "已完成" },
    refund_verifying: { type: "info", label: "退款中" },
};
const columns: DataTableColumns<Reservation> = [
    {
        title: "预约单编号",
        key: "id",
        align: "center",
    },
    {
        title: "创建时间",
        key: "createdTime",
        align: "center",
        render(row: Reservation) {
            return h("div", null, new Date(row.createdTime).toLocaleString());
        },
    },
    {
        title: "审核时间",
        key: "processedTime",
        align: "center",
        render(row: Reservation) {
            return h(
                "div",
                null,
                new Date(row.processedTime!).toLocaleString()
            );
        },
    },
    {
        title: "预约单状态",
        key: "status",
        align: "center",
        render(row: Reservation) {
            return h(
                NTag,
                {
                    type: statusMap[row.status].type as
                        | "default"
                        | "primary"
                        | "success"
                        | "info"
                        | "warning"
                        | "error",
                },
                () => statusMap[row.status].label
            );
        },
    },
    {
        title: "操作",
        key: "actions",
        align: "center",
        render(row: Reservation) {
            return h(
                NButton,
                {
                    size: "small",
                    ghost: true,
                    focusable: false,
                    onClick: () => handleShowDetail(row),
                },
                () => "查看详情"
            );
        },
    },
];

const pagination = reactive({
    page: 1,
    size: 10,
    total: 0,
});

const reservations: Map<number, Reservation[]> = new Map();
const currentReservations = ref<Reservation[]>([]);
const reservationDetails: Map<string, ReservationDetail> = new Map();

const currentReservation = ref<Reservation>();
const currentReservationDetail = ref<ReservationDetail>();

onMounted(async () => {
    try {
        pagination.total = await getReservationCountsByStatus(0);
        if (pagination.total === 0) return;
        getReservations();
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
});

const getReservations = async () => {
    loading.value = true;
    try {
        const res = await getReservationsByStatus(
            0,
            pagination.page,
            pagination.size
        );
        console.log(res);
        currentReservations.value = res;
        reservations.set(pagination.page, res);
    } catch (err) {
        window.NMessage.error((err as Error).message);
    } finally {
        loading.value = false;
    }
};

const handleRefreshPage = async () => {
    pagination.page = 1;
    pagination.total = await getReservationCountsByStatus(0);
    currentReservations.value = [];
    reservations.clear();
    reservationDetails.clear();

    if (pagination.total === 0) return;
    getReservations();
};

const handleChangePage = (current: number) => {
    pagination.page = current;
    if (reservations.has(current)) {
        currentReservations.value = reservations.get(current) || [];
        return;
    }
    getReservations();
};

const handleShowDetail = async (reservation: Reservation) => {
    currentReservation.value = reservation;
    if (reservationDetails.has(reservation.id)) {
        currentReservationDetail.value = reservationDetails.get(
            reservation.id
        )!;
        detailDrawervisible.value = true;
        return;
    }
    try {
        const res = await getReservationDetail(reservation.id);
        currentReservationDetail.value = res;
        reservationDetails.set(reservation.id, res);
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
    detailDrawervisible.value = true;
};
</script>

<style scoped></style>
